angular.
module('console').
component('console', {
  templateUrl:
  'views/app/console/console.template.html',
  controller: function ($scope, $cookies, $http, $window, $location, $rootScope, convert) {

    $scope.fanMode = -1
    $scope.repostID = ''
    $scope.repostID2 = ''
    $scope.repostUID = ''
    $scope.deleteUID = '' 
    $scope.repostFansId = ''
    $scope.deleteCondition = [0,0,0]
    $scope.fansCount = -1
    $scope.followCount = -1
    $scope.tweetCount = -1
    $scope.deleteMode = 0
    $scope.maleOnly = 0
    $scope.repostUID2 = ''
    $scope.repostID3 = ''
    $scope.myAccount = []
    $scope.deleteUidAccount = ''


    
    $http({
      method: 'post',
      url: '/admin/getMyAccount',
    }).success(function (datax) {
      if (datax != undefined) {
        console.log(datax)
        $scope.myAccount = datax.data
        // for (var i  in datax.data){
        // $scope.description = datax.data.description
        // $scope.send = datax.data.send
        // }
      }
    })

    $scope.myAccountFans = function(){
      console.log($scope.fanMode)
      if ($scope.fanMode == 2){
        if ($scope.repostID == ''){
          swal('请输入转发微博id','','error')
          return
        }
      }

      $http({
        method: 'post',
        url: '/admin/runMyAccountFans',
        data : {fanMode : $scope.fanMode,repostID : $scope.repostID2}
      }).success(function (datax) {
        if (datax.code == 201){

        }
        if (datax.code == 200) {
          $scope.fanMode = -1
          $scope.repostID2 = ''
          swal('开始爬取可登录账号的粉丝', '', "success").then(function () {
          })
        }
        if (datax.code == 401) {
          $window.location = '/login'
        }

      })
    }

    $scope.deleteUid = function(index){
      console.log($scope.myAccount,$scope.deleteUidAccount)
      if($scope.deleteUidAccount == ''){
        return
      }
      $http({
        method: 'post',
        url: '/admin/deleteUid',
        data : {accountID : $scope.deleteUidAccount}
      }).success(function (datax) {
        if (datax.code == 201){

        }
        if (datax.code == 200) {
          $scope.deleteUidAccount = ''
          swal('开始根据UID删除粉丝', '', "success").then(function () {
          })
        }
        if (datax.code == 401) {
          $window.location = '/login'
        }

      })
    }

    
    $scope.repostFans = function(){
      // console.log($scope.repostFansId,'111')
        if ($scope.repostFansId == ''){
          swal('请输入转发微博id','','error')
          return
        }

      $http({
        method: 'post',
        url: '/admin/repostFans',
        data : {repostID : $scope.repostFansId}
      }).success(function (datax) {
        if (datax.code == 201){

        }
        if (datax.code == 200) {
          $scope.fanMode = -1
          $scope.repostID2 = ''
          swal('开始向转发的粉丝发送私信', '', "success").then(function () {
          })
        }
        if (datax.code == 401) {
          $window.location = '/login'
        }

      })
    }


    $scope.deleteFans = function(){
      if ($scope.deleteUID == ''){
        swal('请输入登录账号uid','','error')
        return false
      }

      if (($scope.fansCount == -1 ) && ($scope.tweetCount == -1 ) &&($scope.followCount == -1 )){
        swal('删粉条件不能为空','','error')
      }
      console.log($scope.fansCount,$scope.tweetCount,$scope.followCount,$scope.deleteMode,$scope.maleOnly)
      $http({
        method: 'post',
        url: '/admin/deleteMyAccountFans',
        data : {deleteMode : $scope.deleteMode,uid : $scope.deleteUID,condition:[$scope.fansCount,$scope.tweetCount,$scope.followCount,$scope.maleOnly ? 1 :0]}
      }).success(function (datax) {
        if (datax.code == 201){
          swal('该UID不存在，请先登录该账号','','error')
          return
        }
        if (datax.code == 200) {
          // $scope.deleteMode = 0
          // $scope.deleteUID = ''
          // $scope.fansCount = -1
          // $scope.tweetCount = -1
          // $scope.followCount = -1
          swal('开始删除该账号的粉丝', '', "success").then(function () {
          })
        }
        if (datax.code == 401) {
          $window.location = '/login'
        }

      })
    }

    $scope.uploadTxt = function(file){
      console.log('caling')
      if (document.getElementById('file').files[0] == undefined){
        return
      }
      var thisFile = document.getElementById('file').files[0]
      let filename = thisFile.name.replace('.txt','')
      console.log(filename)
      var reader = new FileReader();
      reader.onload = function (e) {
                output = e.target.result;
                console.log(output.length)
                let done = output.split('\n')
                swal.showLoading()
                  $http({
                    method: 'post',
                    url: '/admin/uploadUID',
                    data : {data:done,account:filename}
                  }).success(function (datax) {
                    swal.hideLoading()
                    if (datax.code == 200) {
                      
                      swal('上传成功', '', "success").then(function () {
                      })
                    }
                    if (datax.code == 401) {
                      $window.location = '/login'
                    }

                  }).catch(function(e){
                    swal.close()
                    swal('出错了','','error')
                  })

            };//end onload()
            reader.readAsText(thisFile);

    }

    $scope.uploadTemplate = function(file){
      if (document.getElementById('file').files[0] == undefined){
        return
      }
      var thisFile = document.getElementById('file').files[0]
      var rABS = false;
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";  
          var rABS = false; //是否将文件读取为二进制字符串  
         var pt = this;  
         var workbook; //读取完成的数据  
         // var excelData;  
         var reader = new FileReader(); 
         reader.onprogress = function(e) { 
           let total = thisFile.size;
           this.progress = (e.loaded/total)*100;
            reader.onload = function(e) {
            // var XLSX = require('xlsx');
           try {
             var bytes = new Uint8Array(reader.result);  
             var length = bytes.byteLength;  
             for(var i = 0; i < length; i++) {  
               binary += String.fromCharCode(bytes[i]);  
             }  
             if(rABS) {  
               workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
                 type: 'base64'  
               });  
             }else {  
                               workbook = XLSX.read(binary, {  
                 type: 'binary'  
               });  
             } 
             // excelData = []; 
           } catch(e) {
             console.log('文件类型不正确',e);
             return;
           }
           let tempData = []
           var fromTo = '';
           for (var sheet in workbook.Sheets) {
             if (workbook.Sheets.hasOwnProperty(sheet)) {
               fromTo = workbook.Sheets[sheet]['!ref'];
               let temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
               console.log(temp,'dsds')
               for (var i = 0 ; i < temp.length ; i++){
                console.log(temp[i])
                tempData.push({'uid':temp[i]['UID'],'account':temp[i]['投放广告账号']})
               }
             }
           }

      swal.showLoading()
      $http({
        method: 'post',
        url: '/admin/uploadUID',
        data : {data:tempData}
      }).success(function (datax) {
        swal.hideLoading()
        if (datax.code == 200) {
          
          swal('上传成功', '', "success").then(function () {
          })
        }
        if (datax.code == 401) {
          $window.location = '/login'
        }

      }).catch(function(e){
        swal.close()
        swal('出错了','','error')
      })

         };   
      }
      reader.readAsArrayBuffer(f);  
    }
    var reader = new FileReader();
       if(rABS) {  
         reader.readAsArrayBuffer(thisFile);  
       }else {  
         reader.readAsBinaryString(thisFile);  
       } 

   }

   
   $scope.uploadDeleteUIDlist = function(file){
    if (document.getElementById('deleteUIDlist').files[0] == undefined){
      return
    }
    var thisFile = document.getElementById('deleteUIDlist').files[0]
    var rABS = false;
    FileReader.prototype.readAsBinaryString = function(f) {
      var binary = "";  
        var rABS = false; //是否将文件读取为二进制字符串  
       var pt = this;  
       var workbook; //读取完成的数据  
       // var excelData;  
       var reader = new FileReader(); 
       reader.onprogress = function(e) { 
         let total = thisFile.size;
         this.progress = (e.loaded/total)*100;
          reader.onload = function(e) {
          // var XLSX = require('xlsx');
         try {
           var bytes = new Uint8Array(reader.result);  
           var length = bytes.byteLength;  
           for(var i = 0; i < length; i++) {  
             binary += String.fromCharCode(bytes[i]);  
           }  
           if(rABS) {  
             workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
               type: 'base64'  
             });  
           }else {  
                             workbook = XLSX.read(binary, {  
               type: 'binary'  
             });  
           } 
           // excelData = []; 
         } catch(e) {
           console.log('文件类型不正确',e);
           return;
         }
         let tempData = []
         var fromTo = '';
         for (var sheet in workbook.Sheets) {
           if (workbook.Sheets.hasOwnProperty(sheet)) {
             fromTo = workbook.Sheets[sheet]['!ref'];
             let temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
             console.log(temp,'dsds')
             for (var i = 0 ; i < temp.length ; i++){
              console.log(temp[i]['uid'],temp[i]['微博账号'])
              tempData.push({'uid':temp[i]['uid'],'account':temp[i]['微博账号']})
             }
           }
         }

    swal.showLoading()
    $http({
      method: 'post',
      url: '/admin/uploadneeddeleteuid',
      data : {data:tempData}
    }).success(function (datax) {
      swal.hideLoading()
      if (datax.code == 200) {
        
        swal('上传成功', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    }).catch(function(e){
      swal.close()
      swal('出错了','','error')
    })

       };   
    }
    reader.readAsArrayBuffer(f);  
  }
  var reader = new FileReader();
     if(rABS) {  
       reader.readAsArrayBuffer(thisFile);  
     }else {  
       reader.readAsBinaryString(thisFile);  
     } 

 }

   $scope.downloadTemplate = function(){
        let data = []
    
    data.push(['UID','投放广告账号'])
    data.push(['12345678','tvg'])
    let sheet = XLSX.utils.json_to_sheet(data,{skipHeader: 1})
    let newBook = XLSX.utils.book_new()
    
    XLSX.utils.book_append_sheet(newBook,sheet,'sheet1')
                     const wopts = {
                        bookType: 'xlsx',
                        bookSST: false,
                        type: 'binary'
                    };
    saveAs(new Blob([s2ab(XLSX.write(newBook, wopts))], {
        type: "application/octet-stream"
    }),  "UID导入模板.xlsx");

   }
      function   s2ab(s) {
                if(typeof ArrayBuffer !== 'undefined') {
                    var buf = new ArrayBuffer(s.length);
                    var view = new Uint8Array(buf);
                    for(var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                    return buf;
                } else {
                    var buf = new Array(s.length);
                    for(var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
                    return buf;
                }
            }

   $scope.postFanList = function(){
     console.log($scope.repostID)
    if ($scope.repostUID == ''){
      swal('请输入该微博uid','','error')
      return
    }
    if ($scope.repostID == ''){
      swal('请输入转发微博id','','error')
      return
    }
    $http({
      method: 'post',
      url: '/admin/postFanList',
      data : {repostID : $scope.repostID,repostUID : $scope.repostUID}
    }).success(function (datax) {
      if (datax.code == 200) {
        // $scope.repostID = ''
        // $scope.repostUID = ''
        swal('开始抓取某微博的评论', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }

   $scope.deleteCommenUser = function(){
    if ($scope.repostID3 == ''){
      swal('请输入微博评论id','','error')
      return
    }
    if ($scope.repostUID2 == ''){
      swal('请输入该微博账号uid','','error')
      return
    }
  
    $http({
      method: 'post',
      url: '/admin/deleteCommenUser',
      data : {repostID : $scope.repostID3,repostUID:$scope.repostUID2}
    }).success(function (datax) {
      if (datax.code == 200) {
        // $scope.repostID = ''
        // $scope.repostUID = ''
        swal('开始删除微博转发男粉', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }


  $scope.otherAccountFans = function(){
    $http({
      method: 'get',
      url: '/admin/runOtherAccountFans',
    }).success(function (datax) {
      if (datax.code == 200) {
        swal('开始爬取不可登录账号的粉丝', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }


  $scope.chatFansList = function(){
    $http({
      method: 'get',
      url: '/admin/runChatFansList',
    }).success(function (datax) {
      if (datax.code == 200) {
        swal('开始爬取私信的粉丝', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }


  $scope.otherInteractiveFansList = function(){
    $http({
      method: 'get',
      url: '/admin/runotherInteractiveFansList',
    }).success(function (datax) {
      if (datax.code == 200) {
        swal('开始爬取他账号互动的粉丝', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }


  $scope.updateUserInfo = function(){
    $http({
      method: 'get',
      url: '/admin/updateUserInfo',
    }).success(function (datax) {
      if (datax.code == 200) {
        swal('开始搜索粉丝详情', '', "success").then(function () {
        })
      }
      if (datax.code == 401) {
        $window.location = '/login'
      }

    })
  }




  function formatDate(date) {
    var xdate = new Date(date)
    var year = xdate.getFullYear()
    var day = xdate.getDate()
    var month = xdate.getMonth()
    var hour = xdate.getHours()
    var minute = xdate.getMinutes()
    return String(year) + '-' + String(month + 1) + '-' + String(day) + ' ' + String(addZeroBefore(hour)) + ':' + String(addZeroBefore(minute))
  }

  function formatCellphone(data) {
    console.log(data)
    return String(data).substr(0, 3) + '****' + String(data).substr(7, 10)
  }


  function addZeroBefore(n) {
    return (n < 10 ? '0' : '') + n;
  }

}
})



